package com.laxcen.toydemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.apkfuns.logutils.LogUtils;
import com.laxcen.intelligenttoy.BLE.DataUtils;
import com.laxcen.intelligenttoy.BLEActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;
import util.BackgroundMusic;
import util.DelayHandler;
import util.eventbus.EventBusUtil;
import util.eventbus.MessageEvent;
import util.eventbus.MessageEventType;

public class ConnectActivity extends BLEActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.bt_operation)
    Button btOperation;
    @BindView(R.id.tv_status_point)
    TextView tvStatusPoint;
    @BindView(R.id.tv_status)
    TextView tvStatus;

    @BindView(R.id.tv_hint)
    TextView tvHint;

    @BindView(R.id.ll_btm)
    LinearLayout llBtm;


    private String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};
    private int flag是否连接上 = 0;//当前状态 0.断开  1.连接

    private List<String> list = new ArrayList<>();
    private int antennaNum = -1;//当前开启天线
    private final static int MSG_READ_TIME = 1000;
    private final static int MSG_WHAT_READ = 0x1;
    private boolean isGameMode = false;//是否是游戏模式
    private boolean isSecond = false;//切换游戏题目

    @SuppressLint("HandlerLeak")
    Handler readHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_WHAT_READ:
                    readTagAllLabel();
                    break;
            }
        }
    };

    @OnClick({R.id.bt_operation, R.id.bt_read, R.id.btnGoto, R.id.btn_exit_app})
    void click(View view) {
        switch (view.getId()) {
            case R.id.bt_operation:
                if (Utils.isDoubleClick()) {
                    return;
                }
                switch (flag是否连接上) {
                    case 0:
                        //没有连接上  就执行 连接
                        connectBLE();
                        break;
                    case 1:
                        //已经链接上 就执行 断开
                        disconnectBLE();
                        break;
                }
                break;
            case R.id.bt_read:
                if (Utils.isDoubleClick()) {
                    return;
                }
                showToast("读取中...");
                //读标签
                if (antennaNum == -1) {
                    readTagAllLabel();
                } else {
                    readSingleLabel(antennaNum);
                }
                break;
            case R.id.bt_write:
//                if (Utils.isDoubleClick()) {
//                    return;
//                }
//                //写标签
//                String hexString = et.getText().toString().trim();
//                writeTag(hexString, antennaNum);
                break;
            case R.id.bt_clear:
                //清除
                antennaNum = -1;
                list.clear();
                for (int i = 0; i < 10; i++) {
                    list.add("");
                }


                break;
//            case R.id.btnGoto:
//                startActivity(GameActivity.class);
//                break;
            case R.id.btn_exit_app:
                finish();
                break;
        }
    }

    private static final String BLE_NOT_CONNECT = "状态：托盘未连接\n请按下托盘上小熊鼻子，进行连接";
    private static final String BLE_CONNECT = "状态：托盘已连接\n开始快乐之旅吧";

    @Override
    protected void connectSuccess() {
        btOperation.setText("断开");
        flag是否连接上 = 1;
        tvStatusPoint.setBackgroundResource(R.drawable.green_point);
        tvStatus.setText(BLE_CONNECT);
        Toast.makeText(ConnectActivity.this, "连接成功", Toast.LENGTH_SHORT).show();


        if (isGameMode && SPU.getTagType(mActivity) == 1) {
            readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
        }


        DelayHandler.newHandler().delay(new Runnable() {
            @Override
            public void run() {
                startActivity(GameActivity.class);
            }
        }, 1000);

    }

    @Override
    protected void disConnect() {
        btOperation.setText("连接");
        flag是否连接上 = 0;
        tvStatusPoint.setBackgroundResource(R.drawable.red_point);
        tvStatus.setText(BLE_NOT_CONNECT);
        Toast.makeText(ConnectActivity.this, "已断开", Toast.LENGTH_SHORT).show();
        antennaNum = -1;

    }

    /**
     * 读取所有标签成功
     *
     * @param data
     */
    @Override
    protected void readAllSuccess(byte[] data) {
//        if (antennaNum != -1) {//有选中天线  单标签
//            list.set(antennaNum, DataUtils.bytes2Str(data).replace("\u0000", ""));
//            baseAdapter.notifyItemChanged(antennaNum);
//            return;
//        }
//        list.clear();
//        int i = 0;
//        while (i < data.length) {
//            if (data[i] == -1) {
//                //空的
//                list.add("");
//                i++;
//            } else {
//                byte[] bytes = new byte[8];
//                System.arraycopy(data, i, bytes, 0, 8);
//                judgeType(bytes);
//                i = i + 8;
//            }
//        }
//        if (isGame && SPU.getTagType(mActivity) == 1) {
//            readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
//            toCalculate();
//        }
    }

    @Override
    protected void readAllSuccessToList(List<byte[]> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            byte[] itemBytes = dataList.get(i);
//            Log.d("数据项", "size=" + dataList.size() + " index=" + i + " [" + DataUtils.bytes2Str(itemBytes).replace("\u0000", "") + "]");
        }

        if (antennaNum != -1) {//有选中天线  单标签
            if (dataList != null && !dataList.isEmpty()) {
                list.set(antennaNum, DataUtils.bytes2Str(dataList.get(0)).replace("\u0000", ""));
            } else {
                list.set(antennaNum, "");
            }

            return;
        }
        list.clear();
        for (byte[] data : dataList) {
            if (data.length > 0) { //代表有标签
                judgeType(data);
            } else {//无标签
                list.add("");
            }
        }
        ArrayList<String> tagData = new ArrayList<String>();
        tagData.addAll(list);
        EventBusUtil.post(new MessageEvent(MessageEventType.BLE.FoundTags, tagData));
        if (isGameMode && SPU.getTagType(mActivity) == 1) {
            LogUtils.v("再次循环读取标签");
            readHandler.sendEmptyMessageDelayed(MSG_WHAT_READ, MSG_READ_TIME);
        }
    }

    //判断数值的类型
    private void judgeType(byte[] bytes) {
        if (bytes[0] == 0x00) {
            if (bytes[3] == 0x00) {//unicode编码 后4字节
                byte[] dataBytes = new byte[4];
                System.arraycopy(bytes, 4, dataBytes, 0, 4);
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else if (bytes[3] == 0x01) {//数据位后1字节
                byte[] dataBytes = new byte[1];
                switch (bytes[6]) {
                    case 0x00://汉字的笔划
                    case 0x01://汉语拼音声母韵母
                    case 0x02://通讯辅助设备的所有操作
                    case 0x03://化学元素的编码
                    case 0x04://社交功能模块中的联系人的编码
                    case 0x05://APP所有功能模块的编码
                        System.arraycopy(bytes, 7, dataBytes, 0, 1);
                        break;
                    default:
                        list.add("");
                        break;
                }
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else if (bytes[3] == 0x02) {//英文单词编码 后4字节
                byte[] dataBytes = new byte[4];
                System.arraycopy(bytes, 4, dataBytes, 0, 4);
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else if (bytes[3] == 0x03) {//地名编码 后4字节
                byte[] dataBytes = new byte[4];
                System.arraycopy(bytes, 4, dataBytes, 0, 4);
                list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
            } else {
                list.add("");
            }
        } else if (bytes[0] == 0x01) {//整数编码 后7字节
            byte[] dataBytes = new byte[7];
            System.arraycopy(bytes, 1, dataBytes, 0, 7);
            list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
        } else if (bytes[0] == 0x02) {//浮点数编码 后7字节
            byte[] dataBytes = new byte[7];
            System.arraycopy(bytes, 1, dataBytes, 0, 7);
            list.add(DataUtils.bytes2Str(dataBytes).replace("\u0000", ""));
        } else {
            list.add("");
        }

    }


    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);//横屏
        setContentView(R.layout.activity_connect);
        mActivity = this;
        ButterKnife.bind(this);
        checkPermissions();

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initView();
        changeUI();
    }

    private void initView() {
        isGameMode = true;
    }

    private void changeUI() {
        isGameMode = true;
        SPU.setTagType(mActivity, 1);
        llBtm.setVisibility(View.VISIBLE);
        tvHint.setVisibility(View.GONE);
    }


    /**
     * 权限检查
     */
    private void checkPermissions() {
        if (!EasyPermissions.hasPermissions(this, permissions)) {//检查是否获取该权限
            //第二个参数是被拒绝后再次申请该权限的解释
            //第三个参数是请求码
            //第四个参数是要申请的权限
            EasyPermissions.requestPermissions(this, getString(R.string.app_name)
                    + "缺少重要权限，拒绝则部分功能将无法运行!", 0, permissions);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        startRepeatPromptGbSound();
    }

    private void startRepeatPromptGbSound() {
        if (mBleDevice != null) return;
        DelayHandler.newHandler().delay(new Runnable() {
            @Override
            public void run() {
                BackgroundMusic.instance(ConnectActivity.this).play(R.raw.game_connect_ble_wellcome, false);
            }
        }, 2000).delay(new Runnable() {
            @Override
            public void run() {
                connectBLE();
            }
        }, 15000);
    }

//    private void startAnimationTimer() {
//        int firstDelayMillis = RandomUtil.generateOneNumber(2000, 5000);
//        final Animation animation = AnimationUtils.loadAnimation(this, R.anim.home_menu_button_anim_splash);
//        Handler timerHandler = new Handler();
//        Runnable timerRunnable = new Runnable() {
//            @Override
//            public void run() {
//
//
//                int delayMillis = 2000;
//                timerHandler.postDelayed(this, delayMillis);
//            }
//        };
//        timerHandler.postDelayed(timerRunnable, firstDelayMillis);
//    }

    int scanTimes = 0;

    @Override
    protected void onBleScanCallbackScanFinished() {
        scanTimes++;
        LogUtils.d("蓝牙扫描结束");
        DelayHandler.newHandler().delay(new Runnable() {
            @Override
            public void run() {
                if (mBleDevice == null) {
                    if (scanTimes > 1 && scanTimes % 3 == 1) {
                        BackgroundMusic.instance(ConnectActivity.this).play(R.raw.game_connect_failed_prompt, false);
                    }
                    LogUtils.d("蓝牙扫描结束, 但是没有连接上蓝牙，准备重试");
                    connectBLE();
                } else {
                    LogUtils.d("蓝牙扫描结束, 已经找到蓝牙设备");
                }
            }
        }, 2000);
    }

    @Override
    protected void onBleGattCallbackConnectFail() {
        LogUtils.d("蓝牙连接失败");
        DelayHandler.newHandler().delay(new Runnable() {
            @Override
            public void run() {
                BackgroundMusic.instance(ConnectActivity.this).play(R.raw.game_connect_failed_prompt, false);
                LogUtils.d("蓝牙连接失败，准备重试");
                connectBLE();
            }
        }, 2000);
    }


}
